package com.sunchangming.stmdb;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.sunchangming.stmdb.btree.BTree;

public class DataBase {
	private final Map<String, Table<?, ?>> tables = new HashMap<String, Table<?, ?>>();
	private final RecordManager recman;

	DataBase(java.nio.file.Path dbdir, DBConfig config) throws IOException {
		recman = RecordManagerProvider.createRecordManager(dbdir.resolve("test").toString(), false, 1000);
		for (final String tablename : config.getTableNames()) {
			final TableConfig tc = config.getTableConfig(tablename);
			final BTree tree;
			if (tc.getPersistence().equals(TableConfig.Persistence.DB)) {
				final long recid = recman.getNamedObject(tablename);
				if (recid > 0) {
					tree = BTree.load(recman, recid);
				} else {
					// TODO: nodes per page
					tree = BTree.createInstance(recman, 16);

					recman.setNamedObject("main", tree.getRecid());
				}
			} else
				tree = null;
			tables.put(tablename, new Table(tc, tree));
		}
	}
}
